<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 输入：s = "   -42"
    // 输出：-42

    // 输入：s = "4193 with words"
    // 输出：4193
    //1.判断是否为" "空字符串  2.判断+ -号  3.判断是否为数字
    var myAtoi = function (s) {
      let res = 0;
      let len = s.length;
      let sy = 1;
      for (let i = 0; i < len; i++) {
        let d = s.charAt(i);
        let r = d - "0";
 
        if (d == "+" || d == "-") {
          sy = d == "-" ? -1 : 1;
        }

        if (d !== " " && (r >= 0 || r <= 9)) {
         res = res * 10 + r 
        }
      }

      if (res < Math.pow(-2, 31) || res > Math.pow(2, 31) - 1) {
        return 0;
      }
     
      return res * sy;
    };
 
    console.log(myAtoi("     -42 dsd "));
  </script>
</html>
